﻿using Hwh_Shop.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using WebAPI_DEMO.Models;

namespace Hwh_Shop.Filter
{
	/// <summary>
	/// 结果过滤器/筛选器
	/// </summary>
	public class ResultFilter : Attribute, IResultFilter
	{
		/// <summary>
		/// 在结果执行之后调用的操作...
		/// </summary>
		/// <param name="context"></param>
		public void OnResultExecuted(ResultExecutedContext context)
		{

		}

		/// <summary>
		/// 在结果执行之前调用的一系列操作
		/// </summary>
		/// <param name="context"></param>
		public void OnResultExecuting(ResultExecutingContext context)
		{
			//New了一个统一的返回类ApiResult
			var result = new ApiResult<IActionResult>
			{
				Code = 1,
				Message = "",
				Data = context.Result
			};
			//返回结果之前
			context.Result = new ContentResult
			{
				// 返回状态码设置为200，表示成功
				StatusCode = (int)HttpStatusCode.OK,
				// 设置返回格式
				ContentType = "application/json;charset=utf-8",
				Content = JsonConvert.SerializeObject(result)
			};
		}
	}
}
